
package springredis.com.lei.service.impl;

import java.io.Serializable;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import springredis.com.lei.entity.Article;
import springredis.com.lei.mapper.ArticleMapper;
import springredis.com.lei.service.BlogsService;

/**
 * @author wangyl-910
 * @description
 * @date 2018/2/26
 * @see
 */
@Service
public class BlogsServiceOriginalHashRedisImpl extends ServiceImpl<ArticleMapper, Article> implements BlogsService {

    private static final Logger LOGGER = LoggerFactory.getLogger(BlogsServiceOriginalHashRedisImpl.class);
    @Autowired
    private RedisTemplate<String, Article> redisTemplate;
    //用户的缓存前缀
    private final String USER_CACHE_KEY="USER";
    private final String USER_CACHE_LIST_KEY="USER_LIST";
    @Override
    public boolean removeById(Serializable id) {
        boolean isExist = super.removeById(id);
        if (isExist) {
            // 清除缓存
            LOGGER.debug("清除缓存{}",id);
//            redisTemplate.delete(USER_CACHE_KEY+String.valueOf(id));
            redisTemplate.opsForHash().delete(USER_CACHE_KEY, String.valueOf(id));
        }
        return isExist;
    }

    @Override
    public boolean updateById(Article entity) {
        boolean isExist = super.updateById(entity);
        if (isExist) {
            // 清除缓存
            LOGGER.debug("清除缓存{}",entity.getUserId());
//            redisTemplate.delete(USER_CACHE_KEY+String.valueOf(entity.getTestId()));
            redisTemplate.opsForHash().delete(USER_CACHE_KEY, String.valueOf(entity.getUserId()));
        }
        return isExist;
    }

    @Override
    public Article getById(Serializable id) {
        //先从redis中缓存中获取，===
//        Object obj = redisTemplate.opsForValue().get(USER_CACHE_KEY+String.valueOf(id));
        Object obj = redisTemplate.opsForHash().get(USER_CACHE_KEY, String.valueOf(id));
        if (obj != null) {
            LOGGER.debug("从缓存中获取数据{}",id);
            return (Article) obj;
        }
        //从数据库中获取
        Article user = super.getById(id);
        if (user != null) {
            //将数据放入缓存
            LOGGER.debug("将数据{}放入缓存",id);
            redisTemplate.opsForHash().put(USER_CACHE_KEY, String.valueOf(id), user);
        }
        return user;
    }
    @Override
	public List<Article> listAll() {
		if(redisTemplate.hasKey(USER_CACHE_LIST_KEY)) {
//			map.get(key);
			return redisTemplate.opsForList().range(USER_CACHE_LIST_KEY, 0, Integer.MAX_VALUE);
		}
		List<Article> list =  super.list(null);
		//集合放进来缓存
		redisTemplate.opsForList().leftPushAll(USER_CACHE_LIST_KEY, list);
		return list;
	}
}
